#pragma once
#include "Socket.hpp"
#include "ResolveHttp.hpp"
#include<fstream>
class HttpSerevr
{
private:
    class ThreadDate
    {
    public:
        SocketInfo *client_;
        HttpSerevr *this_;
        ~ThreadDate()
        {
            delete client_;
        }
    };

    std::string ReadHtmlContent(const std::string& path)
    {
        std::ifstream in(path,std::ios_base::binary);
        if(!in.is_open()) return "404";
        // std::string line;
        // std::string content;
        // while(getline(in,line))
        // {
        //     content+=line;
        // }
        std::string content;
        in.seekg(0,std::ios_base::end);
        size_t len=in.tellg();
        in.seekg(0,std::ios_base::beg);
        content.resize(len);
        in.read((char*)content.c_str(),content.size());
        return content;

    }

public:
    HttpSerevr()
    {
    }
    void InIt(const uint16_t &port = 8080, const std::string &ip = "0.0.0.0")
    {
        socket_.CreatSocket();
        socket_.Bind(port, ip);
        socket_.Listen();
    }

    void Run()
    {
        while (true)
        {
            SocketInfo *client = new SocketInfo();
            ThreadDate *date = new ThreadDate();
            date->client_ = client;
            date->this_ = this;
            if (socket_.Accept(*client))
            {
                lg.logmessage(Info, "client_socketfd is %d", client->socketfd_);
                pthread_t tid;
                pthread_create(&tid, nullptr, HttpSerevr::TreadRun, date);
            }
        }
    }

    static void *TreadRun(void *argvs)
    {
        pthread_detach(pthread_self());
        ThreadDate *date = static_cast<ThreadDate *>(argvs);
        // std::string recive_str;
        char buffer[10240];
        int n = 0;
        n = recv(date->client_->socketfd_, buffer, sizeof(buffer) - 1, 0); // 接收数据到buffer
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer;
            std::string recive_str(buffer);
            ResolveHttp resolve;
            resolve.Deserialize(recive_str); // 对数据进行一部分解析
            resolve.DebugPrint();
#pragma region 处理请求
            std::string file_path = date->this_->wwwroot;
            if(resolve.file_path_=="/")
            {
                resolve.file_path_="/home.html";
            }
            file_path+=resolve.file_path_;
            std::string text=date->this_->ReadHtmlContent(file_path);
#pragma endregion
#pragma region 构建响应
            string send_str=resolve.Serialize(text);
#pragma endregion
            send(date->client_->socketfd_,send_str.c_str(),send_str.size(),0);
        }
        close(date->client_->socketfd_);
        delete date;
    }

private:
    Socket socket_;
    std::string wwwroot = "wwwroot";
};